package com.suoluo.zenadmin.service.bigimage;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import com.suoluo.zenadmin.common.CommonResp;
import com.suoluo.zenadmin.dao.bigimage.BigImageDAO;
import com.suoluo.zenadmin.oss.OSSService;
import com.suoluo.zenadmin.oss.OSSService.OSSImageException;
import com.suoluo.zenadmin.service.ServiceException;
import com.suoluo.zenadmin.vo.bigimage.BigImageVO;

public class BigImageServiceImpl implements BigImageService{

	@Autowired
	private BigImageDAO bigImageDAO;
	@Resource(name="ossService")
	private OSSService ossService;

	@Override
	public List<BigImageVO> findListBigImage() {
		
		return bigImageDAO.findListBigImage();
	}

	@Override
	public void saveBigImage(BigImageVO imageVO) {
		String imgName = null;
		try {
			imgName = ossService.putImage(imageVO.getMfile());
			imageVO.setOrigImage(imgName);
			bigImageDAO.saveBigImage(imageVO);
		} catch (OSSImageException e) {
			throw new ServiceException(CommonResp.FAIL_CODE,"图片保存失败！",e);
		} catch (Exception e) {
			ossService.deleteImage(imgName);
			throw new ServiceException(CommonResp.FAIL_CODE,"大图信息保存失败！",e);
		}
		
	}

	@Override
	public BigImageVO findBigImageById(int imageId) {
		
		return bigImageDAO.findBigImageById(imageId);
	}

	@Override
	public void updateBigImage(BigImageVO imageVO) {
		MultipartFile mfile = imageVO.getMfile();
		String imgName = null;
		try {
//			FileEntry oldEntry = new FileEntry(imageVO.getImageUrl());
//			entry = UploadImageManager.replaceFile(mfile, oldEntry);
//			if(entry != null)
//			{
//				imageVO.setImageUrl(entry.getFilePath());
//			}
			if(mfile != null && !mfile.isEmpty())
			{
				imgName = ossService.updateImage(mfile, imageVO.getOrigImage());
				imageVO.setOrigImage(imgName);
			}
			bigImageDAO.updateBigImage(imageVO);
		} catch (OSSImageException e) {
			throw new ServiceException(CommonResp.FAIL_CODE,"保存图片失败！",e);
		}catch (Exception e) {
			ossService.deleteImage(imgName);
			throw new ServiceException(CommonResp.FAIL_CODE,"大图修改失败！",e);
		}
	}

	@Override
	public void deleteBigImage(BigImageVO imagePOJO) {
		//删除图片
		ossService.deleteImage(imagePOJO.getOrigImage());
		//删除数据
		bigImageDAO.deleteBigImage(imagePOJO.getImageId());
	}

	
	@Override
	public List<BigImageVO> findBigImageByType(int imageType) {
		return bigImageDAO.findBigImageByType(imageType);
	}
}
